package cn.htsyb.synergy.utils;

import cn.htsyb.synergy.tester.exception.InvokeException;
import org.apache.commons.lang.NullArgumentException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvokeUtil {
    public static Object invokeMethod(String className, Object[] ctorParams, String methodstr, Object[] funParams)
            throws Exception {
        return invokeMethod(invokeClass(className, ctorParams), methodstr, funParams);
    }

    public static Object invokeMethod(Object classObject, String methodstr, Object[] funParams) throws Exception {
        try {
            if (classObject == null) {
                throw new InvocationTargetException(
                        new NullArgumentException("class Object is null ，can’t invoke  method"));
            }
            if (funParams == null || funParams.length < 0) {
                Method tagMethod = classObject.getClass().getMethod(methodstr);
                return tagMethod.invoke(classObject);

            } else {
                Method tagMethod = classObject.getClass().getMethod(methodstr, getTypeForList(funParams));
                return tagMethod.invoke(classObject, funParams);
            }
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
            throw new Exception(e);
        } catch (InvocationTargetException e) {
            throw new InvokeException("", e);
        }
    }

    private static Object invokeClass(String className, Object[] ctorParams) throws InvocationTargetException {
        try {
            Class<?> tagCls = Class.forName(className);
            if (ctorParams == null || ctorParams.length < 0) {
                return tagCls.newInstance();
            } else {
                return tagCls.getConstructor(getTypeForList(ctorParams)).newInstance(ctorParams);
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException | NoSuchMethodException | SecurityException e) {
            throw new InvocationTargetException(e);
        }
    }

    private static Class<?>[] getTypeForList(Object[] ObjList) {
        if (ObjList != null && ObjList.length > 0) {

            Class<?>[] typeList = new Class[ObjList.length];
            for (int idx = 0; idx < ObjList.length; idx++) {
                typeList[idx] = ObjList[idx].getClass();
            }
            return typeList;
        }
        return null;

    }

}
